<?php
require_once( '../system/smarty.inc' );
require_once( '../system/mdao/Class_M_COST_DM.php' );
require_once( '../system/mdao/Class_M_COST_DM_COUNT.php' );
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );

Class_PWD::valid_auth(AOKI_AUTH_COST_DM,$login['staff_auth']);
$smarty->assign('now_menu', $aokimenu[AOKI_AUTH_COST_DM]["li"]);

$dao       =  new Class_M_COST_DM;
$daoshop   =  new Class_M_COST_DM_COUNT;

if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	if( isset($_GET['id']) && $_GET['id'] != '' ){
		$forms  = $dao->get( $_GET['id'] );
		$forms["begin_date"] = Class_PWD::int8_to_date($forms["begin_date"]);
		$forms["end_date"]   = Class_PWD::int8_to_date($forms["begin_date"]);
		$forms["dm_date"]    = Class_PWD::int8_to_date($forms["dm_date"]);
		
		$wherearr[] = sprintf(" dm_no =  '%s' and matrix_cd  =  '%s' ", $forms['dm_no'], $forms["matrix_cd"] );
		$dbarray = $daoshop->search($wherearr );
		
		//データ整形
		foreach ($dbarray as $k=>$v) {
			$forms["mutirow"] [] = array( "shop_cd"=> $v["shop_cd"], "shop_name" => $v["shop_name"], "count" => $v["count"] );
		}
		
	}else{
		//$forms['auth'] = 0;
	}
	
}else{
	$forms = $_POST;
	if( $forms['mode'] == 'input' ){
		$err     = new Class_ERROR;
		$chk     = $dao->get_checks();
		
		foreach ($chk as $kcol => $chkval) {
			$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
		}
		
	if (isset($forms["shop_cd"])) {
		foreach ($forms["shop_cd"] as $k=>$v) {
			$counterr = $err->check($forms["count"][$k], array( "EXIST","NUM" ) );
			$forms["mutirow"] [] = array( "shop_cd"=> $v, "shop_name" => $forms["shop_name"][$k], "count" => $forms["count"][$k],"errcount" => $counterr );
			
		}
	} 
	
	
		if ( $err->clear ){
			$cols     = $dao->get_cols();
			foreach($cols as $kcol => $val) {
				$values[$kcol] = $forms[$kcol] ;
			}
			
			//$values["media_cd"]        =  Class_M_OTHER::do_media($values["media_name"]);
			$values["begin_date"]   = Class_PWD::date_to_int8 ($values['begin_date']) ;
			$values["end_date"]     = Class_PWD::date_to_int8 ($values['end_date']) ;
			$values["dm_date"]      = Class_PWD::date_to_int8 ($values['dm_date']) ;
			
			
			//桁数チェック
			$maxlens = $dao->get_maxlens();
			foreach ( $maxlens as $k => $v ) {
				$err_mes[$k] =$err->check_size($values[$k], $v);
			}
		}
		
/*
		if ( $err->clear ){
			if( $forms['id'] == '' ){
				$where = sprintf(" pattern_name  = '%s'", $forms['pattern_name'] );
			}else{
				$where = sprintf(" pattern_name = '%s' AND pattern_cd  <> %s", $forms['pattern_name'], $forms['id'] );
			}
			if ( $dao->exits($where) ) {
				$err->clear = false;
				$err_mes['pattern_name'] = '<p class="error">このパターン名は重複しています</p>';
			}
		}
		
*/
		if( $err->clear ){
			
	
			if( $forms['id'] == '' ){
				if ($dao->add0($values)) {
					$forms['id'] = $id;
					$smarty->assign('message', '登録が完了しました。');
					
				} else {
					$smarty->assign('message', '登録が失敗しました。');
				}
			}else{
				
				/*
				if ($dao->edit( $forms['id'], $values )) {
					$smarty->assign('message', '更新が完了しました。');
				} else {
					$smarty->assign('message', '更新が失敗しました。');
				}
				*/
					try {	
						$daoshop->begin_trans();
						if (!$dao->edit( $forms['id'], $values )) {
							throw Exception("DB error");
						}
						$executeflg = TRUE;
						//$disp_ng = $forms["disp_ng"]?$forms["disp_ng"]:0;
						$wherearr[] = sprintf(" dm_no =  '%s'  and matrix_cd =  '%s'", $forms['dm_no'], $forms['matrix_cd']);
						$dbarray = $daoshop->search($wherearr );
						//削除.更新のデータ作成
						foreach($dbarray as $k=>$v) {
							$delflg = TRUE;
							$val_count  = "0";
							foreach($forms["mutirow"] as $kk=>$vv) {
								if ($v["shop_cd"] == $vv["shop_cd"] ) {
									$delflg = FALSE;
									$val_count  = $vv["count"];
									break;
								}
							}
							if ($delflg){
								//$datadel[]  = $v["shop_cd"];
								if ($daoshop->remove($v["id"])) {
								} else {
									$executeflg = FALSE;
								}
								
							} else {
								//$dataedit[] = $v["shop_cd"];
								$values = array();
								$values["count"]  = $val_count;
								if ($daoshop->edit( $v["id"] ,$values)) {
								} else {
									$executeflg = FALSE;
								}
							}
						}
						
						//追加のデータ作成
					
						foreach($forms["mutirow"] as $k=>$v) {
							$taddflg = TRUE;
							foreach($dbarray as $kk=>$vv) {
								if ($v["shop_cd"] == $vv["shop_cd"] ) {
									$taddflg = FALSE;
									break;
								}
							}
							if ($taddflg){
								//$dataadd[] = $v["shop_cd"];
								$values = array();
								$values["dm_no"]        = $forms['dm_no'];
								$values["matrix_cd"]    = $forms['matrix_cd'];
								$values["shop_cd"]      = $v["shop_cd"] ;
								$values["count"]        = $v["count"] ;
								
								if ($daoshop->add0($values)) {
								} else {
									$executeflg = FALSE;
								}
							}
						}
						if  ($executeflg) {
							$daoshop->commit_trans();
							$smarty->assign('message', '更新が完了しました。');
						} else {
							$daoshop->rollback_trans();
							$smarty->assign('message', '更新が失敗しました。');
						}
					} catch (Exception $e) {
						$daoshop->rollback_trans();
						$smarty->assign('message', 'ＤＢエラーで失敗しました。');
					}
				$id = $forms['id'];
			}
			$phase = 'complete';
		}else{
			$phase = 'input';
		}
	}
}

//eflg = 1時,基本情報編集可能
$smarty->assign('eflg', 1);

//eflg = 1時,店舗情報編集可能
$smarty->assign('sflg', 1);

if( isset( $forms ) ) $smarty->assign('forms', $forms);

if( isset( $err_mes ) ) $smarty->assign('err', $err_mes);

if ($phase != 'complete') {
	
}
/*
$electrics = Class_M_OTHER::get_electric_array(PLEASE_SELECT_ARR);
$smarty->assign('electrics', $electrics );
*/

$smarty->assign('phase', $phase );
$smarty->assign('menu',   $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );

$smarty->display('mcost_dm_form.html');
?>